import CustomFieldsMixin from '@/mixins/CustomFields'
import { objDeepCopy, guid } from '@/utils'
import { isEmpty, isArray, isObject } from '@/utils/types'
import NP from 'number-precision'

export default {
  data() {
    return {
    }
  },
  mixins: [CustomFieldsMixin],
  methods: {
    // 添加明细回款字段
    insertTableField(fieldList) {
      let fieldIndex = -1
      let disabled = false
      this.itemsForEach(fieldList, (item, index) => {
        if (item.formType == 'contract') {
          fieldIndex = index
        }
      })
      const contractField = this.getItemWithFromType(fieldList, 'contract')
      if (contractField) {
        disabled = this.getItemIsCanEdit(contractField, this.action.type)
      }
      if (fieldIndex != -1) {
        fieldList.splice(fieldIndex + 1, 0,
          [
            {
              formType: 'contract_field_table',
              name: { receivables: '回款明细', invoice: '开票明细' }[this.crmType],
              disabled,
              stylePercent: 100,
              field: 'contract_field_table',
              fieldName: 'contract_field_table'
            }
          ]
        )
      }
    },
    /**
     * 关联客户 联系人等数据要特殊处理
     */
    getRealParams(field, dataValue) {
      const crmTypeArr = ['customer', 'contacts', 'business', 'leads', 'receivables',
        'supplier_cause', 'purchase_cause', 'sale_cause', 'sale_return_cause', 'retreat_cause', 'warehouse_cause']
      if (crmTypeArr.includes(field.formType)) {
        if (isEmpty(dataValue)) return ''
        if (isArray(dataValue) && dataValue.length > 0 && isObject(dataValue[0])) {
          return dataValue[0][`${field.formType}Id`]
        } else if (isObject(dataValue)) {
          return dataValue.id
        }
        if (isArray(dataValue)) return dataValue[dataValue.length - 1]
        if (['string', 'number'].includes(typeof dataValue)) return dataValue
        return ''
      } else if (field.formType == 'contract') {
        return (dataValue || []).map(item => {
          if (this.crmType == 'receivables') {
            return {
              contractId: item.contractId,
              receivablesPlanId: item.receivablesPlanId,
              currReceivablesMoney: item.currReceivablesMoney,
              remark: item.remark
            }
          } else if (this.crmType == 'invoice') {
            return {
              contractId: item.contractId,
              receivablesIdList: item.receivablesList?.map(i => i.receivablesId) || [],
              // receivablesId: item.receivables?.find(item => item.receivablesId).receivablesId || null, // 回款ID
              currInvoiceMoney: item.currInvoiceMoney, // 本次开票金额
              remark: item.remark
            }
          }
          //  else if (item.receivablesPlanId) {
          //   return {
          //     contractId: item.contractId,
          //     receivablesPlanId: item.receivablesPlanId,
          //     currReceivablesMoney: item.currReceivablesMoney,
          //     remark: item.remark
          //   }
          // } else if (item.receivablesId) {
          //   return {
          //     contractId: item.contractId,
          //     receivablesId: item.receivables?.find(item => item.receivablesId).receivablesId || null, // 回款ID
          //     currInvoiceMoney: item.currInvoiceMoney, // 本次开票金额
          //     remark: item.remark
          //   }
          // }
          return item
        })
      } else if (
        field.formType == 'user' ||
        field.formType == 'structure'
      ) {
        let newDataValue = dataValue || []
        if (isArray(dataValue) && dataValue.length > 0) {
          if (isObject(dataValue[0])) {
            newDataValue = dataValue.map(valueItem => field.formType == 'user'
              ? valueItem.userId
              : valueItem.id)
          }
        } else if (isObject(dataValue)) {
          newDataValue = field.formType == 'user'
            ? dataValue.userId
            : dataValue.id
        }
        return isArray(newDataValue) ? newDataValue.join(',') : newDataValue
      } else if (field.formType == 'file') {
        if (dataValue && dataValue.length > 0) {
          return dataValue[0].batchId
        }
        return ''
      } else if (field.formType == 'category') {
        if (isEmpty(dataValue)) return ''
        if (!isArray(dataValue)) return dataValue
        if (dataValue && dataValue.length > 0) {
          return dataValue[dataValue.length - 1]
        }
        return ''
      } else if (field.formType == 'checkbox') {
        if (isArray(dataValue)) {
          return dataValue.join(',')
        }
        return dataValue
      } else if (field.formType == 'select') {
        return dataValue
      } else if (field.formType == 'detail_table') {
        const fieldExtendList = field.fieldExtendList || []
        const values = []
        const tableValues = Array.isArray(dataValue) ? dataValue : []

        for (let tableValueIndex = 0; tableValueIndex < tableValues.length; tableValueIndex++) {
          const tableValue = tableValues[tableValueIndex]
          // 去除空值数据
          if (!this.getFormValueIsEmpty(fieldExtendList, tableValue)) {
            const batchId = tableValue.batchId || guid()
            const valuesItems = []
            fieldExtendList.forEach(tableField => {
              const copyTableField = objDeepCopy(tableField)
              delete copyTableField.companyId
              copyTableField.value = this.getRealParams(copyTableField, tableValue[copyTableField.fieldName])
              copyTableField.batchId = batchId
              valuesItems.push(copyTableField)
            })
            values.push(valuesItems)
          }
        }

        return values
      } else if (['data_union', 'data_union_multi'].includes(field.formType)) {
        if (isEmpty(dataValue)) return ''
        if (isObject(dataValue)) return dataValue.dataId
        if (isArray(dataValue)) {
          return dataValue
            .map(o => {
              return isObject(o) ? o.dataId : o
            })
            .join(',')
        }
        return dataValue.map(o => o.dataId).join(',')
      }

      return dataValue
    },

    // 获取表格中金额字段
    getMoneyTotal(tableData) {
      const moneyKey = {
        'invoice': 'currInvoiceMoney',
        'receivables': 'currReceivablesMoney'
      }[this.crmType]
      const money = tableData.reduce((prev, curr) => {
        // prev += parseFloat(curr[moneyKey]) || 0
        prev = NP.plus(prev, curr[moneyKey] || 0)
        return prev
      }, 0)
      return money
    },

    /**
     * 判断对象值是否是空
     */
    getFormValueIsEmpty(fieldList, valueObj) {
      for (let index = 0; index < fieldList.length; index++) {
        const field = fieldList[index]
        const value = valueObj[field.fieldName]
        if (field.formType === 'location') {
          if (isObject(value) && (!isEmpty(value.lat) || !isEmpty(value.lng) || !isEmpty(value.address))) {
            return false
          }
        } else if (!isEmpty(value)) {
          return false
        }
      }
      return true
    }

    // 验证回款明细金额
    // validateRepaymentDetail(crmType) {
    //   const array = this.fieldForm['contract']
    //   const money = {
    //     'invoice': this.fieldForm['invoiceMoney'],
    //     'receivables': this.fieldForm['money']
    //   }[crmType]
    //   // 未回款 key映射
    //   const unMoneyKey = {
    //     'invoice': 'unInvoicedMoney',
    //     'receivables': 'unreceivedMoney'
    //   }
    //   // 回款 key映射
    //   const moneyKey = {
    //     'invoice': 'currInvoiceMoney',
    //     'receivables': 'currReceivablesMoney'
    //   }
    //   for (let index = 0; index < array.length; index++) {
    //     const element = array[index]
    //     if (element[moneyKey[crmType]] > element[unMoneyKey[crmType]]) {
    //       const meg = {
    //         'receivables': `回款明细第${index + 1}行回款金额不能大于未回款金额！`,
    //         'invoice': `回款明细第${index + 1}行开票金额不能大于未开票金额！`
    //       }[crmType]
    //       this.$message.error(meg)
    //       return false
    //     }
    //   }
    //   const totalDetailMoney = array.reduce((prev, curr) => {
    //     return prev + parseFloat(curr)
    //   }, 0)
    //   if (totalDetailMoney > money) {
    //     this.$message.error('回款明细总金额不能大于回款金额')
    //     return false
    //   }
    //   return true
    // }
  }

}
